package GearCommands;

import Connections.Peer;
import Gear.Factory;
import Gear.Gear;

import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Implementation of the user command new.
 * Creates a new blank file.
 *
 * @author Davi Mendes
 */
public class GearCommandNew implements GearCommand {

    @Override
    public void execute(String[] args, Gear gear) {
        try {
            if (args.length < 2) throw new IllegalArgumentException("Too few arguments to new command.");

            if (Peer.getInstance().newFile(args[1])) {
                Path n = Files.createFile(FileSystems.getDefault().getPath(Factory.getInstance().getSettings().getGearPath().toString(), (String) Array.get(args, 1)));
                System.out.println("File " + Array.get(args, 1) + " created with success.");
                Peer.getInstance().sycronizeSharedFolder().send();
                n.toFile().setReadOnly();

            } else {
                System.out.println("Error: file " + args[1] + " alreasy exists in the networks, try to download it!");
            }

        } catch (IOException ex) {
            System.out.println("Error while creating file.");
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
        }
    }

}
